const winston = require('winston')
const dayjs = require('dayjs')
const chalk = require('chalk')
const { transports, createLogger, format } = winston
const { combine, timestamp, printf, splat, simple } = format
const fs = require('fs')

if (!fs.existsSync(`logs`)) {
  fs.mkdirSync(`logs`)
}

const formatter = printf(({ level, message, timestamp }) => {
  let t = dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss.sss')
  let l = `[${level.toUpperCase()}]`
  t = chalk.greenBright(t)
  if (level === 'error') {
    l = chalk.redBright(l)
    message = chalk.redBright(message)
  } else {
    l = chalk.blueBright(l)
    message = message.replace(/\[.*\]/, (v) => chalk.yellowBright(v))
  }

  return `${t} ${l}: ${message}`
})
module.exports = ({ config }) => {
  return new createLogger({
    format: combine(timestamp(), splat(), formatter),
    transports: [
      new transports.Console(),
      new transports.File({
        filename: `logs/${config.get('env')}-${dayjs().format(
          'YYYY-MM-DD'
        )}.log`,
        format: combine(
          timestamp(),
          splat(),
          printf(({ level, message, timestamp }) => {
            let t = dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss.sss')
            let l = `[${level.toUpperCase()}]`
            return `${t} ${l}: ${message}`
          })
        ),
      }),
    ],
  })
}
